package com.xindaoapp.framework.activity;

import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.format.Formatter;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.tencent.connect.auth.QQAuth;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.umeng.socialize.controller.RequestType;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.xindaoapp.framework.MainActivity;
import com.xindaoapp.framework.R;
import com.xindaoapp.framework.api.AddClient;
import com.xindaoapp.framework.api.Address;
import com.xindaoapp.framework.api.ConstantsValue;
import com.xindaoapp.framework.application.XindaoApplication;
import com.xindaoapp.framework.base.BaseActivity;
import com.xindaoapp.framework.base.BaseUiListener;
import com.xindaoapp.framework.bean.QQInfo;
import com.xindaoapp.framework.bean.UpdateInfo;
import com.xindaoapp.framework.bean.UserInfo;
import com.xindaoapp.framework.service.UpdateService;
import com.xindaoapp.framework.utils.IRequest;
import com.xindaoapp.framework.utils.ProgressHUD;

/**
 * ============================================================
 * 
 * 版权 : 新道APP (c) 2014
 * 
 * 作者 : 贺奕凯
 * 
 * 版本 : 1.0
 * 
 * 创建日期 : 2014-6-24 下午4:20:10
 * 
 * 描述 : 设置界面
 * 
 * 修订历史 ：
 * 
 * ============================================================
 **/
public class SettingActivity extends BaseActivity implements OnClickListener {
	@ViewInject(R.id.setting_sina)
	private RelativeLayout setting_sina;
	@ViewInject(R.id.setting_qq)
	private RelativeLayout setting_qq;
	@ViewInject(R.id.setting_help)
	private RelativeLayout setting_help;
	@ViewInject(R.id.setting_qingli)
	private RelativeLayout setting_qingli;
	@ViewInject(R.id.setting_version)
	private RelativeLayout setting_version;
	@ViewInject(R.id.setting_net)
	private CheckBox setting_net;
	@ViewInject(R.id.setting_huancun)
	private TextView setting_huancun;

	protected static final int LOGIN_OK = 0;
	protected static final int LOGIN_TRUE = 20;
	private Tencent mTencent;
	private SharedPreferences sp;
	// QQ登录
	public static QQAuth mQQAuth;

	private final Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case LOGIN_OK:
				finish();
				break;
			case LOGIN_TRUE:
				Intent intent = new Intent(SettingActivity.this,
						MainActivity.class);
				startActivity(intent);
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting);
		ViewUtils.inject(this); // 加载注释控件

		mTencent = Tencent.createInstance("10021591",
				this.getApplicationContext());
		sp = getSharedPreferences("userconfig", MODE_PRIVATE);
		

		setListener(); // 注册监听事件
		init(); // 初始化
	}

	private void init() {
		boolean boolean1 = sp.getBoolean("wifi", true);
		setting_net.setChecked(boolean1);
		setting_net.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (!isChecked) {
					Editor editor = sp.edit();
					setting_net.setChecked(isChecked);
					editor.putBoolean("wifi", isChecked);
					editor.commit();
				} else {
					Editor editor = sp.edit();
					setting_net.setChecked(isChecked);
					editor.putBoolean("wifi", isChecked);
					editor.commit();
				}
			}
		});
		
		setting_huancun.setText(getCacheSize());//初始化缓存大小
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.setting_qq: // 腾讯授权
			onClickLoginQQ();
			break;
		case R.id.setting_sina: // 新浪授权
			onClickLoginSina();
			break;
		case R.id.setting_help: // 意见反馈
			Intent help = new Intent(this, HelpActivity.class);
			startActivity(help);
			break;
		case R.id.setting_qingli: // 缓存清理
			new AlertDialog.Builder(SettingActivity.this).setMessage("确认清除缓存?")
			.setNegativeButton("确定", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					if (null == clearTask) {
						clearTask = new ClearTask();
						clearTask.execute("");
					}
					dialog.dismiss();
				}
			}).setPositiveButton("取消", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
				}
			}).create().show();
			break;
		case R.id.setting_version: // 版本更新
			update();
			break;

		default:
			break;
		}
	}

	/**
	 * 版本更新
	 */
	private void update() {
		final ProgressHUD ProgressDialog = ProgressHUD.show(this, "正在加载...", true, true, null);
		XindaoApplication.get().getMoccaApi().checkUpdate(new IRequest<UpdateInfo>() {
			@Override
			public void request(final UpdateInfo t) {
				if (null != ProgressDialog && ProgressDialog.isShowing()) {
					ProgressDialog.dismiss();
				}
				if (null != t && t.version != getVersionCode(SettingActivity.this)) {
					new AlertDialog.Builder(SettingActivity.this).setMessage("发现新版本")
							.setNegativeButton("更新", new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {
//									CommonUtil.startWebView(SettingActivity.this, t.url);
									if (Environment.getExternalStorageState().equals(
											Environment.MEDIA_MOUNTED)) {
										Intent updateIntent = new Intent(getBaseContext(),UpdateService.class);
										updateIntent.putExtra("app_name", "xindaoapp");
										updateIntent
												.putExtra("down_url",t.url);
										startService(updateIntent);

									} else {
										Toast.makeText(getApplicationContext(), "sd卡不可用", 0).show();
									}
								}
							}).setPositiveButton("取消", new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {
								}
							}).create().show();
				}else{
					Toast.makeText(SettingActivity.this, "当前版本为最新版本", Toast.LENGTH_SHORT).show();
				}
			}
		});
	}
	
	/**
	 * 获取版本信息
	 * @param context
	 * @return
	 */
	private static int getVersionCode(Activity context) {
		try {
			return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return -1;
	}

	final UMSocialService mController = UMServiceFactory.getUMSocialService(
			"com.umeng.share", RequestType.SOCIAL);

	private void onClickLoginQQ() {
		IUiListener listener = new BaseUiListener() {
			@Override
			public void onComplete(Object response) {
				QQInfo qq = JSON.parseObject(response.toString(), QQInfo.class);
				ConstantsValue.info = qq;
				ConstantsValue.loginByQQ = true;
				loginByQQ(qq);
				// mController.openUserCenter(getBaseContext(),
				// SocializeConstants.FLAG_USER_CENTER_HIDE_LOGININFO);
			}
		};
		mTencent.login(SettingActivity.this, "all", listener);
	}

	protected void loginByQQ(QQInfo qq) {
		RequestParams params = new RequestParams();
		params.put("conuin", "");
		params.put("conuinsecret", "");
		params.put("conopenid", qq.openid);
		final ProgressHUD ProgressDialog = ProgressHUD.show(this, "正在登录请稍候...",
				true, true, null);
		AddClient.get(Address.QQLOGIN, params, new AsyncHttpResponseHandler() {
			public void onSuccess(int statusCode, String content) {
				if (null != ProgressDialog && ProgressDialog.isShowing()) {
					ProgressDialog.dismiss();
				}
				UserInfo userinfo = JSON.parseObject(content, UserInfo.class);
				if (userinfo.getResult().equals("-1")) {
					Toast.makeText(getApplicationContext(), userinfo.getMsg(),
							Toast.LENGTH_SHORT).show();
					return;
				} else if (userinfo.getResult().equals("0")) {
					ConstantsValue.uid = userinfo.getUserinfo().uid;
					ConstantsValue.setUser(userinfo.getUserinfo());
					ConstantsValue.isLogin = true;
					Toast.makeText(getApplicationContext(), "登录成功",
							Toast.LENGTH_SHORT).show();
					Editor edit = sp.edit();
					edit.putString("username", userinfo.userinfo.username);
					edit.putString("password", "");
					edit.commit();
					handler.sendEmptyMessage(LOGIN_OK);
				} else if (userinfo.getResult().equals("101")) {
					if (ConstantsValue.isLogin) {
						bindQQ();
					} else {
						Intent intent = new Intent(SettingActivity.this,
								BindActivity.class);
						intent.putExtra("tittle", "绑定QQ帐号");
						startActivity(intent);
						finish();
					}
				}
				ConstantsValue.cookieStore = AddClient.getClient().getCookie();
				super.onSuccess(statusCode, content);
			}

			@Override
			public void onFailure(Throwable error, String content) {
				if (null != ProgressDialog && ProgressDialog.isShowing()) {
					ProgressDialog.dismiss();
				}
				super.onFailure(error, content);
			}
		});
	}

	private void bindQQ() {
		RequestParams params = new RequestParams();
		params.put("conuin", "");
		params.put("conuinsecret", "");
		params.put("conopenid", ConstantsValue.info.openid);
		final ProgressHUD ProgressDialog = ProgressHUD.show(this, "正在加载...",
				true, true, null);
		AddClient.get(Address.BINDQQ, params, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int statusCode, String content) {
				if (null != ProgressDialog && ProgressDialog.isShowing()) {
					ProgressDialog.dismiss();
				}
				UserInfo userinfo = JSON.parseObject(content, UserInfo.class);
				if (userinfo.getResult().equals("0")) {
					ConstantsValue.uid = userinfo.getUserinfo().uid;
					ConstantsValue.setUser(userinfo.getUserinfo());
					ConstantsValue.isLogin = true;
					Editor edit = sp.edit();
					edit.putString("username", userinfo.userinfo.username);
					edit.putString("password", "");
					edit.commit();
					handler.sendEmptyMessage(LOGIN_TRUE);
					Toast.makeText(getApplicationContext(), "绑定成功",
							Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(getApplicationContext(), userinfo.getMsg(),
							Toast.LENGTH_SHORT).show();
				}
				super.onSuccess(statusCode, content);
			}

			@Override
			public void onFailure(Throwable error, String content) {
				if (null != ProgressDialog && ProgressDialog.isShowing()) {
					ProgressDialog.dismiss();
				}
				super.onFailure(error, content);
			}
		});
	}

	private void onClickLoginSina() {
		// 创建微博实例
		// mWeiboAuth = new WeiboAuth(this,
		// com.xindaoapp.happypet.application.Constants.APP_KEY,
		// com.xindaoapp.happypet.application.Constants.REDIRECT_URL,
		// com.xindaoapp.happypet.application.Constants.SCOPE);
		// mSsoHandler = new SsoHandler(SettingActivity.this, mWeiboAuth);
		// mSsoHandler.authorize(new AuthListener());
		Toast.makeText(getBaseContext(), "待添加", 0).show();
	}
	
	private ClearTask clearTask;

	private class ClearTask extends AsyncTask<String, Integer, Boolean> {

		@Override
		protected Boolean doInBackground(String... params) {
			File cache = SettingActivity.this.getCacheDir();
			File[] child = cache.listFiles();
			for (int i = 0; i < child.length; i++) {
				try {
					deleteFile(child[i]);
				} catch (Exception e) {}
			}
			cache.delete();
			return true;
		}

		private void deleteFile(File file) {
			if (file.exists()) {
				if (file.isDirectory()) {
					File[] child = file.listFiles();
					for (int i = 0; i < child.length; i++) {
						deleteFile(child[i]);
					}
				}
				file.delete();
			}
		}

		@Override
		protected void onPostExecute(Boolean result) {
			setting_huancun.setText(getCacheSize());
			Toast.makeText(getApplicationContext(), "缓存清除成功", Toast.LENGTH_SHORT).show();
		}

	}
	
	private CharSequence getCacheSize() {
		File cacheDir = this.getCacheDir();
		long size = getSize(cacheDir);
		return Formatter.formatFileSize(this, size);
	}
	
	public long getSize(File file) {
		// 判断文件是否存在
		if (file.exists()) {
			// 如果是目录则递归计算其内容的总大小，如果是文件则直接返回其大小
			if (!file.isFile()) {
				// 获取文件大小
				File[] fl = file.listFiles();
				long ss = 0;
				for (File f : fl)
					ss += getSize(f);
				return ss;
			} else {
				long ss = file.length();
				return ss;
			}
		} else {
			Toast.makeText(getApplicationContext(), "缓存文件为空", Toast.LENGTH_SHORT).show();
		}
		return 0;
	}

	/**
	 * 事件监听
	 */
	public void setListener() {
		setting_sina.setOnClickListener(this);
		setting_qq.setOnClickListener(this);
		setting_net.setOnClickListener(this);
		setting_help.setOnClickListener(this);
		setting_qingli.setOnClickListener(this);
		setting_version.setOnClickListener(this);
	}

}
